package sg.edu.nus.comp.qa.calculator;

import sg.edu.nus.comp.qa.utils.WordNetDictionary;

public class WordDistanceCalculator implements Calculator {

	public static String REGEX = " ";
	private String[] wordsA;
	private String[] wordsB;
	private int[][] memory;
	
	@Override
	public double calculate(String a, String b) {
		wordsA = a.split(REGEX);
		wordsB = b.split(REGEX);
		initializeMemory(wordsA.length, wordsB.length);
		return 0.2 * doCalculate(0, 0);
	}
	private int doCalculate(int indexA, int indexB) {
		int cost = 0;
		if (indexA == wordsA.length) {
			return wordsB.length - indexB;
		} else if (indexB == wordsB.length) {
			return wordsA.length - indexA;
		} else {
			if (memory[indexA][indexB] >= 0)
				return memory[indexA][indexB];
			if (!wordsA[indexA].equalsIgnoreCase(wordsB[indexB]))
				cost = 1;
			int distance = Math.min(
					Math.min(doCalculate(indexA + 1, indexB) + 1,
							doCalculate(indexA, indexB + 1)),
					doCalculate(indexA + 1, indexB + 1) + cost);
			memory[indexA][indexB] = distance;
			return distance;
		}
	}

	private void initializeMemory(int sizeA, int sizeB) {
		memory = new int[sizeA][sizeB];
		for (int i = 0; i < sizeA; i++)
			for (int j = 0; j < sizeB; j++)
				memory[i][j] = -1;
	}

}
